package com.example.happiness.utils;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.example.happiness.config.AlipayConfig;
import com.example.happiness.constant.Message;
import com.example.happiness.mapper.OrderMapper;
import com.example.happiness.pojo.Order;
import com.example.happiness.pojo.alipay.AliPay;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Component
public class AlipayUtil {

    @Autowired
    private AlipayConfig alipayConfig;
    @Autowired
    OrderMapper orderMapper;

    public String alipay(AliPay aliPay) throws AlipayApiException {
        // 1. 创建Client，通用SDK提供的Client，负责调用支付宝的API
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getGatewayUrl(), alipayConfig.getAppId(),
                alipayConfig.getAppPrivateKey(), alipayConfig.getFormat(), alipayConfig.getCharset(),
                alipayConfig.getAlipayPublicKey(), alipayConfig.getSignType());

        // 设置商家自身的订单参数,这里的参数名一定要跟app支付接口2.0文档里面的一样！！！每个参数什么意思文档里面都有写！！！
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", aliPay.getTraceNo());
        bizContent.put("total_amount", BigDecimal.valueOf(aliPay.getTotalAmount()));
        bizContent.put("subject", aliPay.getSubject());
        bizContent.put("product_code", "QUICK_MSECURITY_PAY");


        // 2. 创建 Request并设置Request参数
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest ();  // 发送请求的 Request类
        request.setNotifyUrl(alipayConfig.getNotifyUrl()); // 这里设置我们接收支付宝响应的URL
        request.setReturnUrl(alipayConfig.getResulturl()); // 这里设置我们接收支付宝响应的URL
        request.setBizContent(bizContent.toString());


        //这里和普通的接口调用不同，使用的是sdkExecute
        // 3. 执行请求
        AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
        System.out.println(response.getBody());
        //返回生成的字符串
        return response.getBody();
    }

    public void alipayNotify(HttpServletRequest request) throws Exception{
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }

            String sign = params.get("sign");
            String content = AlipaySignature.getSignCheckContentV1(params);
            boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, alipayConfig.getAlipayPublicKey(), alipayConfig.getCharset()); // 验证签名
            // 支付宝验签
            if (checkSignature) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));

                // 查询订单
                Order order = orderMapper.selectByPrimaryKey(params.get("out_trade_no"));
                System.out.println(order.getAddress());
                order.setState(Message.TWO);
                orderMapper.updateOrderStateByOrderid(order);
            }
        }
    }

    public void refund(HttpServletResponse response, String orderid, String price) throws IOException, AlipayApiException {
        System.out.println(orderid+","+price);
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getGatewayUrl(), alipayConfig.getAppId(),alipayConfig.getAppPrivateKey(),
                alipayConfig.getFormat(), alipayConfig.getCharset(), alipayConfig.getAlipayPublicKey(), alipayConfig.getSignType());
        //设置请求参数
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();

        //商户订单号，必填
        String out_trade_no = new String(orderid);


        //需要退款的金额，该金额不能大于订单金额，必填
        String refund_amount = new String(price);
        //标识一次退款请求，同一笔交易多次退款需要保证唯一。如需部分退款，则此参数必传；不传该参数则代表全额退款
        String out_request_no = new String(UUID.randomUUID().toString());
        // 字符转义很重要
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"refund_amount\":\""+ refund_amount +"\","
                + "\"out_request_no\":\""+ out_request_no +"\"}");
        //请求
        String result = alipayClient.execute(alipayRequest).getBody();
        //输出
        out.println(result);//以下写自己的订单退款代码
        System.out.println("返回结果={}"+result);
        Order order = new Order();
        order.setOrderid(orderid);
        order.setState(Message.SIX);
        orderMapper.updateOrderStateByOrderid(order);
    }
}
